<?php
namespace PFT;
// use \PFT\Db;

// include_once '/var/www/html/new/d/module/common/Db.class.php';
// $db_conf = include('/var/www/html/new/d/module/common/db.conf.php');
// Db::Conf($db_conf['remote_1']);
// Db::ConnectRef();

//价格分组
class PriceGroup {

	const _PRICE_GROUP_TABLE_ = 'pft_price_group';

	public static function test() {
		var_dump(Db::fetchAll("select * from pft_price_group"));die;
	}

	/**
	 * 新建分组
	 * @param int $sid 供应商id
	 * @param string $name 分组名
	 */
	public static function addNewGroup($sid, $name) {
		if (self::hasGroupExists($sid, $name)) {
			return true;
		}
		// self::test();
		$data = array(
			'sid' => $sid, 
			'name' => $name,
		);
		$result = Db::insert($data, self::_PRICE_GROUP_TABLE_);
		return $result ? true : false;
	}

	/**
	 * 更新分组
	 * @param  [type] $gid  [description]
	 * @param  [type] $name [description]
	 * @param  [type] $sid  [description]
	 * @return [type]       [description]
	 */
	public static function updateGroup($gid, $name, $sid) {
		$result = false;
		if (self::belongTo($gid, $sid)) {
			$data = array(
				'name' => $name
			);
			$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $gid);
		}
		return $result ? true : false;
	}	

	/**
	 * 将分销商加入分组
	 * @param  int $gid 分组id
	 * @param  int $did 分销商id
	 * @return bool
	 */
	public static function joinGroup($gid, $did, $sid) {
		// self::followGroupPrice($did, $gid, $sid);
		$dids_sql = 'select id,dids,default_inc from '.self::_PRICE_GROUP_TABLE_.' where id=:id limit 1';
		$dids_result = Db::fetch($dids_sql, array(':id' => $gid));
		if ($dids_result['dids']) {
			$dids = explode(',', $dids_result['dids'] . ',' . $did);
			$dids = implode(',', array_unique($dids));
		} else {
			$dids = $did;
		}
		$data = array('dids' => $dids);
		$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $dids_result['id']);
		if ($result) {
			self::followGroupPrice($did, $gid, $sid);
			// $default_inc = json_decode($dids_result['default_inc']);
			// if ($default_inc) {
			// 	foreach ($default_inc as $pid =>  $price) {
			// 		$group = array($gid => $price / 100); 
			// 		self::savePriceForProduct($pid, $group, array());
			// 	}
			// }
		}
		return $result ? true : false;
	}

	/**
	 * 从指定分组移动指定的分销商
	 * @param  int $did  分销商id
	 * @param  int $from 分组id
	 * @param  int $to   分组id
	 * @return bool
	 */
	public static function moveGroup($did, $from = 0, $to = 0, $sid) {
		//跟随分组的分销权限
		self::followGroupLimit($did, $from, $to, $sid);
		if ($from == 0) {
			return self::joinGroup($to, $did, $sid);
		}
		$from_group_info = self::getGroupById($from);
		if (!$from_group_info) {
			return false;
		}
		if (!$from_group_info['dids']) {
			return false;
		}
		$from_dids_arr = explode(',', $from_group_info['dids']);
		if (($key = array_search($did, $from_dids_arr)) === false) {
			return false;
		}
		unset($from_dids_arr[$key]);
		$data = array('dids' => implode(',', $from_dids_arr));
		$result1 = Db::update($data, self::_PRICE_GROUP_TABLE_, $from_group_info['id']);
		if ($result1) {
			if (!$to) {
				return true;
			}
			$to_group_info = self::getGroupById($to);
			if ($to_group_info['dids']) {
				$to_dids_arr = explode(',', $to_group_info['dids']);
				$to_dids_arr[] = $did;
				$to_dids = implode(',', $to_dids_arr);
				$data = array('dids' => implode(',', $to_dids_arr));
			} else {
				$to_dids = $did;
			}
			$data = array('dids' => $to_dids);
			$result2 = Db::update($data, self::_PRICE_GROUP_TABLE_, $to_group_info['id']);
			if ($result2) {
				self::followGroupPrice($did, $to_group_info['id'], $sid);
			}
			return $result2 ? true : false;
		}
		return false;
	}

	public static function disabledProductByGroup($pid, $gid, $sid) {
		$group_info = self::getGroupById($gid, $sid);
		if (!$group_info) {
			return false;
		}
		if (!$group_info['default_inc']) {
			return false;
		}
		$default_inc = json_decode($group_info['default_inc'], true);
		if (isset($default_inc[$pid])) {
			unset($default_inc[$pid]);
			$data = array('default_inc' => json_encode($default_inc));
			$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $group_info['id']);
			if (!$result) {
				return false;
			}
			if ($group_info['dids']) {
				$did_arr = explode(',', $group_info['dids']);
				foreach ($did_arr as $did) {
					self::disabledProductByDistributor($pid, $did, $sid);
				}
			}
			return true;
		} 
		return false;
	}

	public static function disabledProductByDistributor($pid, $did, $sid) {
		$data = array(
			'pid' => $pid,
			'did' => $did
		);
		if (self::isSelfProduct($pid, $sid)) {
			$url = 'http://dev.12301.cc/priceset_dt.php';
		} else {
			$url = 'http://dev.12301.cc//priceset_sale.php';
			$data['act'] = 'turnoffEvo';
		}
		$result = self::curl($url, $data);
		return $result['status'] == 'success' ? true : false;
	}

	/**
	 * 去掉某个分组指定产品的分销权限
	 * @param  int $sid [description]
	 * @param  int $gid [description]
	 * @param  int $pid [description]
	 * @return [type]      [description]
	 */
	// public static function disabledProduct($sid, $gid, $pid) {
	// 	$group_info = self::getGroupById($gid, $sid);
	// 	if (!$group_info) {
	// 		return false;
	// 	}
	// 	$disabled_pids = $group_info['disabled_pids'];
	// 	if ($disabled_pids) {
	// 		$disabled_pids .= ','.$pid;
	// 		$pids_arr = explode(',', $disabled_pids);
	// 		$disabled_pids = implode(',', array_unique($pids_arr));
	// 	} else {
	// 		$disabled_pids = $pid;
	// 	}
	// 	$data = array('disabled_pids' => $disabled_pids);
	// 	$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $group_info['id']);
	// 	return $result ? true : false;
	// 	// var_dump($disabled_pids);die;
	// }

	/**
	 * 允许某个分组指定产品的分销权限
	 * @param  int $sid [description]
	 * @param  int $gid [description]
	 * @param  int $pid [description]
	 * @return [type]   [description]
	 */
	public static function allowProduct($sid, $gid, $pid) {
		$group_info = self::getGroupById($gid, $sid);
		if (!$group_info) {
			return false;
		}
		$is_self = self::isSelfProduct($pid, $sid);
		if ($is_self) {
			$sale_sql = "select id,fid,pids 
						from pft_product_sale_list 
						where aid=:sid and fid in ({$group_info['dids']})";
			$sale_list = Db::fetchAll($sale_sql, array(':sid' => $sid));
			foreach ($sale_list as $sale) {
				$pids_arr = explode(',' ,$sale['pids']);
				if (!in_array($pid, $pids_arr)) {
					$pids_arr[] = $pid;
					$data = array('pids' => implode(',', $pids_arr));
					Db::update($data, 'pft_product_sale_list', $sale['id']);
					//日志记录
				}
			}
		} else {
			// $data = array(
			// 	'did' => $did,
			// 	'src_pris' => array(
			// 		$supply_id.'_'.$pid =>  
			// 		)
			// );
			// $update_sql = "update pft_p_apply_evolute
			// 			set status = 0 
			// 			where sid=:sid and fid in ({$group_info['dids']}) and pid=:pid";
			// $res = Db::execute($update_sql, array(':sid' => $sid, ':pid' => $pid));
			// var_dump($res);die;

		}
		$disabled_pids = $group_info['disabled_pids'];
		if ($disabled_pids) {
			$pids_arr = explode(',', $disabled_pids);
			if (($key = array_search($pid, $pids_arr)) !== false) {
				unset($pids_arr[$key]);
			}
			$disabled_pids = implode(',', array_unique($pids_arr));
		}
		$data = array('disabled_pids' => $disabled_pids);
		$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $group_info['id']);
		return $result ? true : false;
	}


	/**
	 * 跟随分组的分销权限
	 * @param  [type] $did  [description]
	 * @param  [type] $from [description]
	 * @param  [type] $to   [description]
	 * @param  [type] $sid  [description]
	 * @return [type]       [description]
	 */
	private static function followGroupLimit($did, $from, $to, $sid) {
		if ($from && $to) {
			$from_group = self::getGroupById($from, $sid);
			$to_group = self::getGroupById($to, $sid);
			if ($to_group['default_inc']) {
				$to_default_inc = json_decode($to_group['default_inc'], true);
				$to_pids = array_keys($to_default_inc);
				$from_default_inc = array();
				if ($from_group['default_inc']) {
					$from_default_inc = json_decode($from_group['default_inc'], true);
				}
				foreach ($from_default_inc as $pid => $price) {
					if (!in_array($pid, $to_pids)) {
						self::disabledProductByDistributor($pid, $did, $sid);
					}
				}
			}
		} elseif ($from == 0 && $to) {
			//自供应产品
			$sql = "select pids from pft_product_sale_list where aid={$sid} and fid={$did} limit 1";
			if ($supply_pids = Db::fetch($sql)) {
				if ($supply_pids['pids']) {
					$supply_pids = $supply_pids['pids'];
					if ($supply_pids == A) {
						$supply_pids = array();
						$sql = "select id as pid 
							from uu_products 
							where apply_did={$sid} and p_status in (0,3,4,5) and apply_limit=1";
						$tmp = Db::fetchAll($sql);
						foreach ($tmp as $item) {
							$supply_pids[] = $item['pid'];
						}
					} else {
						$supply_pids = explode(',', $supply_pids);
					}
					//获取转分销权限
					$sql = "select e.pid
						from `pft_p_apply_evolute` e left join uu_products p on e.pid=p.id 
						left join pft_member m on e.sid=m.id 
						left join uu_land l on p.contact_id=l.id 
						where e.fid={$sid} and e.status=0 and e.active=1 and lvl<3 
				 		and l.status=1 and p.apply_limit=1 and p.p_status in (0,1)";
				 	$tmp = Db::fetchAll($sql);

				 	$dis_pids = array();
				 	foreach ($tmp as $item) {
				 		$dis_pids[] = $item['pid'];
				 	}
				 	$sql="select pid from `pft_p_apply_evolute` 
				 		where sid={$sid} and fid={$did} and status=0 and pid in (".implode(',', $dis_pids).")";
				 	$tmp2 = Db::fetchAll($sql);
				 	$dis_pids = array();
				 	if ($tmp2) {
				 		foreach ($tmp2 as $item) {
				 			$dis_pids[] = $item['pid'];
				 		}
				 	}
				 	$pids = array_merge($supply_pids, $dis_pids);
				 	$to_info = self::getGroupById($to, $sid);
				 	if (!$to_info || !$to_info['default_inc']) {
				 		$to_pids = array();
				 	} else {
				 		$default_inc = json_decode($to_info['default_inc'], true);
				 		$to_pids = array_keys($default_inc);
				 	}
			 		foreach ($pids as $pid) {
			 			if (!in_array($pid, $to_pids)) {
			 				self::disabledProductByDistributor($pid, $did, $sid);
			 			}
			 		}
				}
			}
		} elseif ($from && $to == 0) {
			// echo aaaa;die;
			$from_info = self::getGroupById($from, $sid);
		 	if ($from_info && $from_info['default_inc']) {
		 		$default_inc = json_decode($from_info['default_inc'], true);
		 		$pids = array_keys($default_inc);
		 		foreach ($pids as $pid) {
		 			self::disabledProductByDistributor($pid, $did, $sid);
		 		}
		 	}
		} else {
			return;
		}
	}

	/**
	 * 跟随分组价格
	 * @param  [type] $did [description]
	 * @param  [type] $gid [description]
	 * @return [type]      [description]
	 */
	private static function followGroupPrice($did, $gid, $sid) {
		$group_info = self::getGroupById($gid, $sid);
		if ($group_info['default_inc']) {
			$price_arr = json_decode($group_info['default_inc'], true);
			foreach ($price_arr as $pid => $price) {
				$distributor[$did] = $price / 100;
				$group = array();
				if (self::isSelfProduct($pid, $sid)) {
					$apply_did = 0;
				} else {
					$apply_did = Db::fetch("select apply_did from uu_products where id={$pid} limit 1");
					$apply_did = $apply_did['apply_did'];
				}
				self::savePriceForProduct($pid, $group, $distributor, $apply_did);
			}
		}
	} 



	public static function savePriceForProduct($pid, $group, $distributor, $sid = 0) {
		foreach ($group as $gid => $price) {
			if ((int)$price > 0) {
				self::setDefaultSettlePrice($gid, $pid, $price * 100);
			}
			$group_info = self::getGroupById($gid);
			if (!$group_info['dids']) {
				continue;
			}
			$did_arr = explode(',', $group_info['dids']);
			foreach ($did_arr as $did) {
				$distributor[$did] = $price;

			}
		}
		$data = array(
			'sid' => $sid,
			'pid' => $pid,
			'pri' => $distributor
		);
		$url = 'http://dev.12301.cc/adjusting_dt.php';
		$result = self::curl($url, $data);
		return $result['status'] == 'success' ? true : false;
	}

	public static function savePriceForDistributorByGroup($gid, $price, $sid) {
		$group_info = self::getGroupById($gid, $sid);
		if (!$group_info) {
			return false;
		}
		$dids = explode(',', $group_info['dids']);
		$url = 'http://dev.12301.cc/a/1.php';//提到属性中去
		$data = array(
			'pid' => array_keys($price),
			'pri' => $price,
			'shows' => array_keys($price)
		);
		foreach ($data['pid'] as $key => $pid) {
			self::setDefaultSettlePrice($gid, $pid, $data['pri'][$pid] * 100);
		}

		foreach ($dids  as $did) {
			$data['did'] = $did;
			self::curl($url, $data);
		}
		return true;//todo
	}

	public static function savePriceForDistributorByDid($did, $price) {
		$url = 'http://dev.12301.cc/a/1.php';//提到属性中去
		$data = array(
			'did' => $did,
			'pid' => array_keys($price),
			'pri' => $price,
			'shows' => array_keys($price)
		);
		self::curl($url, $data);
		return true;//todo
	} 

	public static function savePriceForDisByGroup($gid, $src, $set, $sid) {
		$group_info = self::getGroupById($gid, $sid);
		if (!$group_info) {
			return false;
		}
		foreach ($set as $key => $item) {
			if ($item > 0) {
				$tmp = explode('_', $key);
				self::setDefaultSettlePrice($gid, $tmp[0], $item * 100);
			}
		}
		if ($group_info['dids']) {
			$did_arr = explode(',', $group_info['dids']);
			foreach ($did_arr as $did) {
				self::savePriceForDisByDid($did, $src, $set);
			}
		}
		return true;
	}

	public static function savePriceForDisByDid($did, $src, $set) {
		$url = 'http://dev.12301.cc/priceset_sale.php';//提到属性中去
		$src_pids = array();
		foreach ($src as $key => $item) {
			$tmp = explode('_', $key);
			$src_pids[$key] = $tmp[0];
		}
		$pid = array();
		foreach ($set as $key => $item) {
			$tmp = explode('_', $key);
			$pid[$tmp[1]] = $tmp[0];
		}
		$data = array(
			'did' => $did,
			'src_pris' => $src,
			'src_pids' => $src_pids,
			'set_pris' => $set,
			'pid' => $pid
		);
		$result = self::curl($url, $data);
		return $result['status'] ? true : false;
	}


	/**
	 * 判断是否是自供应产品
	 * @param  int  $pid 产品id
	 * @param  int  $sid 供应商id
	 * @return boolean      [description]
	 */
	public static function isSelfProduct($pid, $sid) {
		$sql = "select apply_did from uu_products where id=:id";
		$info = Db::fetch($sql, array(':id' => $pid));
		// var_dump($info);
		return $info['apply_did'] == $sid;
	}

	/**
	 * 删除分组
	 * @param  int $sid 供应商id
	 * @param  int $gid 分组id
	 * @return boolean     [description]
	 */
	public static function deleteGroup($sid, $gid) {
		$sql = 'delete from '.self::_PRICE_GROUP_TABLE_.' where id=:id and sid=:sid';
		// var_dump($sid, $gid);die;
		$result = Db::execute($sql, array(':id' => $gid, ':sid' => $sid));

		return $result ? true : false;
	}

	/**
	 * 设置指定分组指定产品的默认差价
	 * @param int $gid          分组id
	 * @param int $pid          产品id
	 * @param int $settle_price 差价（分）
	 */
	public static function setDefaultSettlePrice($gid, $pid, $settle_price) {
		$group_info = self::getGroupById($gid, $sid);
		$price_arr = json_decode($group_info['default_inc'], true);

		if ($price_arr) {
			$price_arr[$pid] = $settle_price;
		} else {
			$price_arr = array($pid => $settle_price);
		}
		$data = array(
			'default_inc' => json_encode($price_arr)
			);
		$result = Db::update($data, self::_PRICE_GROUP_TABLE_, $group_info['id']);
		return $result ? true : false;
	}

	/**
	 * 判断某个分组是否属于指定供应商
	 * @param  int $gid 分组id
	 * @param  int $sid 供应商id
	 * @return bool
	 */
	public static function belongTo($gid, $sid) {
		$sql = 'select id from '.self::_PRICE_GROUP_TABLE_.' where id=:id and sid=:sid';
		$result = Db::fetch($sql, array(':id' => $gid, ':sid' => $sid));
		return $result ? true : false;
	}

	/**
	 * 根据分组id获取分组信息
	 * @param  [type] $gid [description]
	 * @return [type]      [description]
	 */
	public static function getGroupById($gid, $sid = null) {
		if ($sid) {
			$extra = 'and sid=:sid';
			$bind = array(':id' => $gid, ':sid' => $sid);
		} else {
			$bind = array(':id' => $gid);
		}
		$dids_sql = "select * from ".self::_PRICE_GROUP_TABLE_." where id=:id {$extra} limit 1";
		return Db::fetch($dids_sql, $bind);
	}

	/**
	 * 获取指定供应商下属的分组
	 * @return [type] [description]
	 */
	public static function getGroupsBySid($sid) {
		$sql = 'select id,name,dids,default_inc 
				from ' . self::_PRICE_GROUP_TABLE_ . ' 
				where sid = :sid';
		return Db::fetchAll($sql, array(':sid' => $sid));
	}

	/**
	 * 判断分组是否已经存在
	 * @param  int  $sid  		供应商id
	 * @param  string  $name 	分组名
	 * @return boolean       [description]
	 */
	public static function hasGroupExists($sid, $name) {
		$sql = 'select count(*) as count  
				from '.self::_PRICE_GROUP_TABLE_.' 
				where sid=:sid and name = :name 
				limit 1';
		$result = Db::fetch($sql, array(':sid' => $sid, ':name' => $name));
		return $result['count'] ? true : false;
	}

	private static function curl($url, $data) {
		$data['session'] = $_SESSION;
		$data['auth'] = 'admin';
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query($data));
		$return = curl_exec ( $ch );
		// var_dump($return);die;
		curl_close ( $ch );
		return json_decode($return, true); 
		
	}
} 